package com.yxj.dries.data;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.yxj.dries.api.WebService;
import com.yxj.dries.model.User;

import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;
import javax.inject.Singleton;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@Singleton
public class UserRepository  {

    private final WebService webService;
    private final UserDao userDao;
    private final Executor executor;

    @Inject
    public UserRepository(WebService webService, UserDao userDao, Executor executor) {
        this.webService = webService;
        this.userDao = userDao;
        this.executor = executor;
    }

    public LiveData<User> getUser(String userId) {

        refreshUser(userId);

        return userDao.load(userId);
    }

    private void refreshUser(String userId) {

        executor.execute(() -> {
            boolean userExists = userDao.hasUser(userId);
            if (!userExists) {
                try {
                    Response<User> response = webService.getUser(userId).execute();
                    userDao.save(response.body());
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });

    }

//    public static Long FRESH_TIMEOUT = TimeUnit.DAYS.toMillis(1);

}
